//
//  ST_BTVideoParticularViewController.swift
//  BTVideo
//
//  Created by DouLei on 2019/8/6.
//  Copyright © 2019 DouLei. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import RealmSwift


class ST_BTVideoParticularViewController: ST_BTLightBarViewController {

    var user:ST_BTUserinfo?{
        didSet{
            
            if let myId = ST_BTUserInfoManager.shared.current_account_info?.accid, user?.accid == myId{
                isMyvideo = true
            }else{
                isMyvideo = false
            }
        }
    }
    
    var isMyvideo = false
    
//    是朋友
    var is_friends = false
    
    var model = UserPreviewVideoModel()
    
    override func viewDidDisappear(_ animated: Bool) {
        
        super.viewDidDisappear(animated)
        
        NotificationCenter.default.removeObserver(self)
        
        if operateBtn.isSelected == false{
            self.pause_or_replay(sender: operateBtn)
        }
   
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        own_navigation_bar.backgroundColor = Color.clear
        
        left_nav_btn.setImageForAllStates(ST_ImageUtils.imageName("返回_white")!)
        
        right_nav_btn.setImageForAllStates(ST_ImageUtils.imageName("UserCenter_mycenter_icon_更多")!)
        
        view.insertSubview(cover_image_view, belowSubview: own_navigation_bar)
        cover_image_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        view.insertSubview(topGradient, belowSubview: own_navigation_bar)
        topGradient.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(100)
            make.top.equalToSuperview().offset(0)
        }
        
        let bottomGradHeight = iPhoneXSeries ? 200.cgFloat : 200
//        view.addSubview(bottomGradient)
        view.insertSubview(bottomGradient, belowSubview: own_navigation_bar)
        bottomGradient.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(bottomGradHeight)
        }
        
        
        view.addSubview(textField)
        
        let textFieldBottom = iPhoneXSeries ? 44 : 20
        
        if isMyvideo || is_friends{
            
            textField.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(15)
                make.height.equalTo(36)
                make.right.equalToSuperview().offset(-15)
                make.bottom.equalToSuperview().offset(-textFieldBottom)
            }
            
        }else{
            
            view.addSubview(love_btn)
            view.addSubview(super_love_btn)
            super_love_btn.snp.makeConstraints { (make) in
                make.right.equalToSuperview().offset(-15)
                make.bottom.equalToSuperview().offset(-textFieldBottom+7)
                make.width.height.equalTo(48)
            }
            love_btn.snp.makeConstraints { (make) in
                make.width.height.equalTo(48)
                make.right.equalTo(super_love_btn.snp.left).offset(-10)
                make.centerY.equalTo(super_love_btn)
            }
            
            textField.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(15)
                make.height.equalTo(36)
                make.right.equalTo(love_btn.snp.left).offset(-15)
                make.bottom.equalToSuperview().offset(-textFieldBottom)
            }
        }
        
        view.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-65)
            make.bottom.equalTo(textField.snp.top).offset(-20)
        }
        
        
//        bind model
        
        cover_image_view.pin_setImage(from: model.cover_img.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
        
        if model.screen_type == 1{
            cover_image_view.contentMode = UIView.ContentMode.scaleAspectFill
        }else{
            cover_image_view.contentMode = UIView.ContentMode.scaleAspectFit
        }
        
        content_label.text = model.intro
        
        self.play()
     
        setUpBarrageView()
        
        
    }
    
    //设置弹幕
    func setUpBarrageView(){
        
        //        弹幕
    
        
        self.view.addSubview(top_barrage_container_view)
        top_barrage_container_view.snp.makeConstraints { (make) in
            make.height.equalTo(140)
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(100-40+statusBarHeight)
        }
        
        self.view.addSubview(mid_barrage_container_view)
        mid_barrage_container_view.snp.makeConstraints { (make) in
            make.height.equalTo(40)
            make.left.right.equalTo(self.view)
            make.centerY.equalTo(self.view).offset(-15)
        }
        
        
        self.view.addSubview(bottom_barrage_container_view)
        bottom_barrage_container_view.snp.makeConstraints { (make) in
            make.height.equalTo(40)
            make.left.right.equalTo(self.view)
            make.centerY.equalTo(self.view.snp.centerY).offset(140)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(ready_play_barrage_handle(noti:)), name: Notification.Name.ready_play_barrage, object: nil)
        
        ST_BT2KBarrageAdapter.shared.add_will_req(videoId: model.id)
        
        
        view.addSubview(operateBtn)
        operateBtn.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: statusBarHeight+50, left: 15, bottom: BTSafeAreaBottom+70, right: 15))
        }
        
    }
    
    
    override var hidden_right_btn: Bool {
        set {
            super.hidden_right_btn = newValue
        }
        get {
            return false
        }
    }
    
    
    
    //    MARK: - dismiss Animate

    override func left_click() {
        dismiss_handle()
    }
    
    func dismiss_handle(){
        
        for item in self.view.subviews{
            if item != self.cover_image_view{
                item.removeFromSuperview()
            }
        }
        
//        self.playerLayer?.removeFromSuperlayer()
        
        goback_previous_controller()
    }
    
    //    MARK: - Barrage Properties
    
    var barrageIdx:Int?
    
    
    
    lazy var top_barrage_container_view:ST_mutilLineBarrageView = {
        let control = ST_mutilLineBarrageView()
        return control
    }()
    
    
    lazy var mid_barrage_container_view:ST_OneLineBarrageView = {
        let control = ST_OneLineBarrageView()
        return control
    }()
    
    lazy var bottom_barrage_container_view:ST_OneLineBarrageView = {
        let control = ST_OneLineBarrageView()
        return control
    }()
    
    var currentBarrage = ST_EditBarrageModel.init(text: "", color: UIColor.white, direction: ST_BarrageDirection.top)
    
//    MARK: - Play Video
    var player:AVPlayer?
    
    
    var playerLayer:AVPlayerLayer?
    
    // 0 :播放中，1:暂停
    private var playState = 0
    
    fileprivate func stop(){
        
        self.playerLayer?.removeFromSuperlayer()
        self.player?.pause()
        self.player = nil
        playState = 1
    }
    
    deinit {
        
//        self.stop()
//        print("停止了播放视频")
    }
    
    fileprivate func play(){
        
        guard  let playUrl = URL.init(string: model.full_url)  else {
            return
        }
       
        
        
        let palyerItem = AVPlayerItem(url: playUrl)
        //创建ACplayer：负责视频播放
        self.player = AVPlayer.init(playerItem: palyerItem)
        
        self.player?.rate = 1.0//播放速度 播放前设置
        //创建显示视频的图层
        let playerLayer = AVPlayerLayer.init(player: player)
        
        if model.screen_type == 1{
            playerLayer.videoGravity = .resizeAspectFill
        }
        
        playerLayer.frame = self.view.bounds
        self.playerLayer = playerLayer
        
        self.view.layer.insertSublayer(playerLayer, above: self.cover_image_view.layer)
        
        guard let player = self.player else { return  }
        
        player.play()
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.player_did_finish_playing(note:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: palyerItem)
        
    }
    
    @objc func player_did_finish_playing(note: Notification) {
        
        //        print("播放完成")
        
        if self.operateBtn.isSelected{
            return
        }
        
        if let playerItem = note.object as? AVPlayerItem{
            
            if let currentItem = self.player?.currentItem,playerItem == currentItem{
                
                playState = 1
                if let player = self.player{
                    player.seek(to: CMTime.zero)
                    player.play()
                    playState = 0
                }
                
                return
            }
        }
        
        
    }
    
//    MARK: - Properties
    
//
//    lazy var pauseSignImageView:UIImageView = {
//        let control = UIImageView.init(image: ST_ImageUtils.imageName("pause"))
//        control.frame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: 104/2.0, height: 106/2.0))
//        control.center = self.view.center
//        return control
//    }()
    
    lazy var operateBtn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
//        control.backgroundColor = Color.clear
        
        control.setImage(ST_ImageUtils.imageName("pause"), for: UIControl.State.selected)
        
        control.addTarget(self, action: #selector(pause_or_replay(sender:)), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    lazy var topGradient:UIImageView = {
        
        let control = UIImageView()
        
        control.image = ST_ImageUtils.imageName("UserCenter_IndexItem_img_顶部蒙层")
        
        return control
    }()
    
    lazy var cover_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.backgroundColor = Color.black
        return control
    }()
    
    lazy var textField:UITextField = {
        let control = UITextField()
        control.backgroundColor = Color.init(hexString: "#F2F4F7", transparency: 0.3)
        control.cornerRadius = 6
        control.textColor = Color.white
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.placeholder = "发个有爱的弹幕吧~"
        control.setPlaceHolderTextColor(UIColor.white)
        control.layer.sublayerTransform = CATransform3DMakeTranslation(10, 0, 0)
        control.returnKeyType = .send
        control.delegate = self
        control.enablesReturnKeyAutomatically = true
        return control
    }()
    
    
    lazy var love_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("mycenter_icon_详情喜欢")!)
        control.addTarget(self, action: #selector(love_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    

    
    lazy var super_love_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
    
        control.setImageForAllStates(ST_ImageUtils.imageName("mycenter_icon_超级喜欢")!)
        control.addTarget(self, action: #selector(super_love_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    

    lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.white
        control.numberOfLines = 0
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        return control
    }()
    
    lazy var bottomGradient:UIImageView = {
        
        let control = UIImageView()
        //        control.contentMode = UIView.ContentMode.scaleToFill
        control.isUserInteractionEnabled = false
        //        let imageName = iPhoneXSeries ? "mycenter_bg_底部蒙层":"mycenter_bg_底部蒙层6s"
        //
        //        let image = UIImage.init(named: imageName)
        control.image = ST_ImageUtils.imageName("UserCenter_mycenter_bg_视频底部蒙层")
        
        return control
    }()
    
    
//    MARK: - Event
    @objc func pause_or_replay(sender:UIButton){
        
        guard let player = self.player else { return  }
        
        if sender.isSelected {
            player.play()
            sender.isSelected = false
            
        }else{
            player.pause()
            sender.isSelected = true
        }
    }
    
    override func right_click() {
        
        let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: UIAlertController.Style.actionSheet)
        
        alert.addAction(title: "取消", style: UIAlertAction.Style.cancel, isEnabled: true, handler: nil)
        
        let actionText = isMyvideo ? "设为封面":"举报"
        
        alert.addAction(title: actionText, style: UIAlertAction.Style.default, isEnabled: true) { (ac) in
            
            if self.isMyvideo{
                self.set_current_with_cover()
            }else{
                self.report()
            }
        }
        
        if isMyvideo{
            
            alert.addAction(title: "删除视频", style: UIAlertAction.Style.default, isEnabled: true) { (ac) in
                
                self.deleteVideo()
            }
        }
        
        
        self.present(alert, animated: true, completion: nil)
        
    }
    
    @objc func love_handle(){
        
        guard let account = ST_BTUserInfoManager.shared.current_account_info,let eData = account.extra_data else{return }
        
        //          会员过期 并且 没有滑动次数
//        if BTExpiredMember() {
//            
//            if  eData.like_times < 1{
//                
//                return
//            }
//        }
        
        let param = ["target_accid" : self.user?.accid ?? ""] as [String : Any]
        
        JVrequest(PH.likeSomebadyApi,parameters:param, success: { (json) in
            
            print("喜欢某个用户:\(json.rawString() ?? "空数据")")
            
            let realm = try! Realm()
            
            try! realm.write {
                account.extra_data?.like_times = eData.like_times - 1
            }
            
            if json["data"]["mutual_like"].boolValue{
                
                guard let user = self.user else{return}
                
                ST_BTBootController.shared.matchSuccess(accid: user.accid, avatar: user.avatar, nickname: user.nickname)
                
            }else{
                ToastHud(text: "喜欢成功！！", view: self.view)
            }
            
            
            
        }, failure: { (code, str) in
            
            
            ToastHud(text: str, view: self.view)
        })
    }
    
    @objc func super_love_handle(){
        
        guard let current_user = ST_BTUserInfoManager.shared.current_account_info , let count = current_user.extra_data?.super_like,count > 0 else {
            
            ToastHud(text: "每天登陆伴心就能获得1个超级喜欢哦！", view: self.view)
            
            return
        }
        
        
        
        
        JVrequest(PH.sendSuperLikeApi,parameters:["target_accid": self.user?.accid ?? ""] ,success: { (json) in
            
            let mutual_like = json["data"]["mutual_like"].boolValue
            
            if mutual_like{
                
                guard let user = self.user else{return}
                
                ST_BTBootController.shared.matchSuccess(accid: user.accid, avatar: user.avatar, nickname: user.nickname)
                
            }else{
                
                ToastHud(text: "发送超级喜欢成功！", view: self.view)
            }
            
            let realm = try! Realm()
            
            try! realm.write {
                current_user.extra_data?.super_like = count - 1
            }
            
        }) { (code, err) in
            
            
            ToastHud(text: err, view: self.view)
            
        }
        
        
    }
    
    func set_current_with_cover(){
        
        
        JVrequest(PH.setCoverVideoApi,parameters:["video_id":model.id],success: { (json) in
            
            ToastHud(text: "设置成功", view: self.view)
            
            NotificationCenter.default.post(name: NSNotification.Name.my_user_info_updated, object: nil)
            
        }) { (code, error) in
            ToastHud(text: error, view: self.view)
        }
        
        
    }
    
    
    func report(){
        
        let vc = ST_ReportPersonController()
        vc.userId = self.user?.accid ?? ""
        vc.video_id = self.model.id
        let nav = UINavigationController.create_hiding_bar_navigation_controller(rootViewController: vc)
        GlobalPresent(toController: nav)
    }
    
    
    func deleteVideo(){
        
        JVrequest(PH.deleteVideoApi,parameters:["video_id":model.id],success: { (json) in
            
            ToastHud(text: "删除成功", view: self.view)
            
            NotificationCenter.default.post(name: NSNotification.Name.my_user_info_updated, object: nil)
            
            self.view.isUserInteractionEnabled = false
            
            main_thread_execute(afterDelay: 2, block: {
                
                self.dismiss_handle()
                
                self.view.isUserInteractionEnabled = true
            })
            
        }) { (code, error) in
            ToastHud(text: error, view: self.view)
        }
    }
    
//    MARK:- Direction && Status Bar
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return UIStatusBarStyle.lightContent
    }
    
    override var shouldAutorotate: Bool{
        return false
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return UIInterfaceOrientationMask.portrait
    }
}
